package com.pureut.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pureut.storage.domain.*;
import com.pureut.storage.dto.IncomingMaterialPrintingDetailDto;
import com.pureut.storage.dto.IncomingMaterialPrintingDto;
import com.pureut.storage.dto.UnitConversionDto;
import com.pureut.storage.dto.WarehouseStringDto;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.IncomingMaterialPrintingService;
import com.pureut.storage.service.WarehouseService;
import com.pureut.storage.util.UnitUtil;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.vo.IncomingMaterialPrintingVo;
import com.pureut.storage.vo.OneKeyWarehousingVo;
import com.pureut.storage.vo.UpdatePrintStatusVo;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.domain.R;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.order.api.RemotePurchaseOrderService;
import com.sale.system.api.*;
import com.sale.order.api.vo.UpdatePurchaseOrderDataVo;
import com.sale.system.api.domain.SysAuxiliary;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.dto.SysApiOrderSupplierManagementDto;
import com.sale.system.api.domain.dto.SysDocumentResultDto;
import com.sale.system.api.model.MaterialUnitDto;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 * 来料打印实现层
 * Author:C
 * Date:2022/12/26 14:57
 * @DESC
 */
@Service
@RequiredArgsConstructor
public class IncomingMaterialPrintingServiceImpl implements IncomingMaterialPrintingService {


    private final IncomingMaterialPrintingMapper incomingMaterialPrintingMapper;

    private final PurchaseReceiptMapper purchaseReceiptMapper;

    private final IncomingMaterialPrintingDetailMapper incomingMaterialPrintingDetailMapper;

    private final PurchaseReceiptDetailMapper purchaseReceiptDetailMapper;

    private final WmsStockInfoMapper wmsStockInfoMapper;

    private final WarehouseService warehouseService;

    private final UnitUtil unitUtil;

    private final SubcontractReceiptDetailMapper subcontractReceiptDetailMapper;

    private final SubcontractReceiptMapper subcontractReceiptMapper;

    private final WipCompletionMapper wipCompletionMapper;

    private final WipCompletionDetailMapper wipCompletionDetailMapper;

    @DubboReference
    RemotePurchaseOrderService remotePurchaseOrderService;

    @DubboReference
    RemoteUnitService remoteUnitService;

    @DubboReference
    RemoteSysSupplierService remoteSysSupplierService;

    @DubboReference
    RemoteSysConverterService remoteSysConverterService;

    @DubboReference
    RemoteMenuService remoteMenuService;

    @DubboReference
    RemoteDocumentService remoteDocumentService;


    /**
     * 采购列表
     *
     * @param incomingMaterialPrintingVo
     * @return
     */
    @Override
    public TableDataInfo<IncomingMaterialPrintingDto> getIncomingMaterial(IncomingMaterialPrintingVo incomingMaterialPrintingVo, PageQuery pageQuery) {
        //打印状态
        List<SysDictData> printStatusArray = CacheUtils.get(CacheNames.SYS_DICT, "print_status");
        Map<String, String> printStatusMap = printStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        Page<IncomingMaterialPrintingDto> list = incomingMaterialPrintingMapper.getList(pageQuery.build(), incomingMaterialPrintingVo);
        List<IncomingMaterialPrintingDto> records = list.getRecords();
        //供应商
        Map<String, String> supplierMap = remoteSysSupplierService.getOpenSupplierFinance();
        for (IncomingMaterialPrintingDto entity : records) {
            //供应商
            entity.setSupplierName(supplierMap.get(entity.getSupplierCode()));
            //获取采购打印状态
            entity.setPrintStatusDict(printStatusMap.get(String.valueOf(entity.getPrintStatus())));
            entity.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(entity.getDocumentType())));
        }
        return TableDataInfo.build(list);
    }

    /**
     * 采购打印详情
     *
     * @param id
     * @return
     */
    @Override
    public IncomingMaterialPrintingDto getPrintView(long id) throws Exception {

        IncomingMaterialPrintingDto incomingMaterialPrintingDto = incomingMaterialPrintingMapper.getPrintById(id);

        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();

        //获取该数据下的明细
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageSize(99999);
        pageQuery.setPageNum(99999);
        Page<IncomingMaterialPrintingDetailDto> detailList = incomingMaterialPrintingDetailMapper.getDetailList(pageQuery.build(), id);
        List<IncomingMaterialPrintingDetailDto> incomingMaterialPrintingDetails = detailList.getRecords();

        BigDecimal totalWeight = new BigDecimal(0);
        for (IncomingMaterialPrintingDetailDto entity : incomingMaterialPrintingDetails) {
            totalWeight = totalWeight.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
        }
        //辅助属性
        List<SysAuxiliary> statsArray = CacheUtils.get(CacheNames.SYS_GINSENG + "_" + incomingMaterialPrintingDto.getTenantId(), String.valueOf(incomingMaterialPrintingDto.getMaterialId()));
        incomingMaterialPrintingDto.setAuxiliaryAttribute(statsArray);
        //单位
        incomingMaterialPrintingDto.setMaterialUnit(incomingMaterialPrintingDetails.get(0).getMaterialUnit());
        incomingMaterialPrintingDto.setUnitDict(unitByCodeToMap.get(incomingMaterialPrintingDetails.get(0).getMaterialUnit()).getUnitName());
        //转换
        UnitConversionDto unitConversionDto = unitUtil.atWillunitConversion(incomingMaterialPrintingDetails.get(0).getConvertUnit(), incomingMaterialPrintingDetails.get(0).getMaterialCode(),
            String.valueOf(totalWeight), incomingMaterialPrintingDetails.get(0).getMaterialId());
        if (unitConversionDto != null) {
            incomingMaterialPrintingDto.setUnitConversion(unitConversionDto.getMaterialMoreUnitNumber());
        }
        //获取供应商数据
        if(incomingMaterialPrintingDto.getSupplierCode() != null){
            R<SysApiOrderSupplierManagementDto> supplierByCode = remoteSysSupplierService.getSupplierByCode(incomingMaterialPrintingDto.getSupplierCode());
            incomingMaterialPrintingDto.setSupplierName(supplierByCode.getData().getSupplierName());
        }

        //计算平均净重
        BigDecimal divide = totalWeight.divide(new BigDecimal(incomingMaterialPrintingDto.getQuantityBatch()), 0);
        incomingMaterialPrintingDto
            //本批净重
            .setNetWeight(Double.parseDouble(totalWeight.toString()))
            //本批数量
            .setQuantityBatch(incomingMaterialPrintingDto.getQuantityBatch())
            //平均净重
            .setAverageNetWeight(Double.parseDouble(divide.toString()));
        return incomingMaterialPrintingDto;
    }


    /**
     * 一键入库
     *
     * @param oneKeyWarehousingVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean oneKeyWarehousing(OneKeyWarehousingVo oneKeyWarehousingVo) {
        //通过库位编码获取仓库信息
        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(oneKeyWarehousingVo.getKwCode());
        //获取单据配置信息
        Long menuId = remoteMenuService.getIdByMenuName("采购入库");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);
        //获取采购打印信息
        IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectById(oneKeyWarehousingVo.getId());
        if (incomingMaterialPrinting.getPrintStatus() == 3) {
            //获取采购打印明细信息
            Page<IncomingMaterialPrintingDetailDto> page = new Page<>();
            Page<IncomingMaterialPrintingDetailDto> detailList = incomingMaterialPrintingDetailMapper.getDetailList(page, oneKeyWarehousingVo.getId());
            List<IncomingMaterialPrintingDetailDto> records = detailList.getRecords();
            //根据批次号查询采购入库明细
            List<PurchaseReceiptDetail> purchaseReceiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>()
                .lambda().eq(PurchaseReceiptDetail::getBatchNo, records.get(0).getBatchNo()));
            for (PurchaseReceiptDetail entity : purchaseReceiptDetailList) {
                //如果配置了交接明细为待交接否则为已完成
                if (sysDocument.getDocHandoverMark() == 1) {
                    entity.setStatus(2);
                } else {
                    entity.setStatus(3);
                }
                entity.setWarehouseInBy(LoginHelper.getUsername());
                entity.setWarehouseMessage(warehouseCode.getCombinationName());
                entity.setWarehouseInTime(new Date());
            }

            purchaseReceiptDetailMapper.updateBatchById(purchaseReceiptDetailList);

            //获取采购入库信息
            PurchaseReceipt byId = purchaseReceiptMapper.selectById(purchaseReceiptDetailList.get(0).getReceiptId());
            //单位
            MaterialUnitDto data1 = remoteUnitService.getUnitDataByCode(Long.parseLong(byId.getMaterialUnit())).getData();
            String unitQuantity = data1.getUnitQuantity();

            //获取仓库数据
            List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, purchaseReceiptDetailList.get(0).getBatchNo()));
            for (WmsStockInfo entity : wmsStockInfoList) {

                entity.setWsiWarehourse(String.valueOf(warehouseCode.getCkId()));
                entity.setWsiReservoirArea(String.valueOf(warehouseCode.getKqId()));
                entity.setWsiStorageLoaction(String.valueOf(warehouseCode.getKwId()));
                entity.setWsiWarehourseInfo(warehouseCode.getCombinationName());
                entity.setWsiDocNum(byId.getReceiptNo());
                entity.setWsiConnectNum(byId.getPurchaseOrderNo());
                entity.setWsiGorssWeight(purchaseReceiptDetailList.get(0).getGrossWeight());
                entity.setWsiNetWeight(purchaseReceiptDetailList.get(0).getNetWeight());
                entity.setWsiMaterialStatus(2);
                entity.setUnitPrice(byId.getUnitPrice());
                entity.setMaterialUnit(Long.parseLong(byId.getMaterialUnit()));
                if (unitQuantity != null) {
                    entity.setWsiMinunitNum(Integer.parseInt(unitQuantity));
                }
                entity.setWsiMaterialGrade("1");
            }
            //修改仓库数据
            wmsStockInfoMapper.updateBatchById(wmsStockInfoList);

            //获取入库总重量
            BigDecimal totalNetWeight = new BigDecimal(0);
            for (WmsStockInfo entity : wmsStockInfoList) {
                totalNetWeight = totalNetWeight.add(new BigDecimal(String.valueOf(entity.getWsiNetWeight())));
            }

            //校验该采购入库的全部明细状态是否都为已入库，如果不全是就修改为入库中，否则就修改为已完成
            List<PurchaseReceiptDetail> receiptDetailList = purchaseReceiptDetailMapper.selectList(new QueryWrapper<PurchaseReceiptDetail>().lambda().eq(PurchaseReceiptDetail::getReceiptId, byId.getId()));
            boolean isTrue = true;
            for (PurchaseReceiptDetail entity : receiptDetailList) {
                if (entity.getStatus() == 1) {
                    isTrue = false;
                    break;
                }
            }
            //获取本次入库的重量与单据原重量之和
            double v;
            if (byId.getActualQuantity() != null) {
                BigDecimal add = totalNetWeight.add(new BigDecimal(byId.getActualQuantity()));
                v = Double.parseDouble(add.toString());
            } else {
                v = Double.parseDouble(totalNetWeight.toString());
            }
            //实际量
//            double aDouble = Double.parseDouble(byId.getActualQuantity());
            //每一次将实际量和计划量进行比较
            double plannedWeight = byId.getPlannedWeight();
            boolean b = (int) Math.round(v) >= (int) Math.round(plannedWeight);

            //如果实际量大于等于计划量并且采购入库的全部明细状态为已入库
            if (isTrue && b) {
                if (sysDocument.getDocHandoverMark() == 1) {
                    byId.setStatus(3);
                } else {
                    byId.setStatus(5);
                }
            } else {
                byId.setStatus(2);
            }

//            double plannedWeight = byId.getPlannedWeight();
//            boolean b = (int) Math.round(v) >= (int) Math.round(plannedWeight);
//            if (isTrue && b) {
//                byId.setStatus(5);
//            } else {
//                byId.setStatus(2);
//            }
            byId.setActualQuantity(String.valueOf(v));
            byId.setWarehousingWarehouse(warehouseCode.getCkId());
            if (byId.getWarehousingNum() == null) {
                byId.setWarehousingNum(purchaseReceiptDetailList.size());
            } else {
                byId.setWarehousingNum(byId.getWarehousingNum() + purchaseReceiptDetailList.size());
            }
            purchaseReceiptMapper.updateById(byId);

//            // 将数据回传至采购订单
//            UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
//            updatePurchaseOrderDataVo.setActualQuantity(String.valueOf(v));
//            updatePurchaseOrderDataVo.setPurchaseOrderNo(byId.getPurchaseOrderNo());
//            remotePurchaseOrderService.updateOrderData(updatePurchaseOrderDataVo);

            incomingMaterialPrinting.setPrintStatus(4);
            return incomingMaterialPrintingMapper.updateById(incomingMaterialPrinting) > 0;
        } else {
            throw new GlobalException("只能操作待入库的数据");
        }
    }


    /**
     * 根据唯一标识修改状态(feign调用)
     *
     * @param returnStatusVo
     * @return
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean getDataByOnlyMark(ReturnStatusVo returnStatusVo) {
//
//        IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getOnlyMark, returnStatusVo.getOnlyMark()));
//
//        incomingMaterialPrinting.setPrintStatus(2);
//        List<ResultMaterialVo> materialList = returnStatusVo.getMaterialList();
//        String averageTare = materialList.get(0).getAverageTare();
//
//        //根据id获取明细数据
//        List<IncomingMaterialPrintingDetail> incomingMaterialPrintingDetails = incomingMaterialPrintingDetailMapper.selectList(new QueryWrapper<IncomingMaterialPrintingDetail>().lambda().eq(IncomingMaterialPrintingDetail::getPrintId, incomingMaterialPrinting.getId()));
//        for (IncomingMaterialPrintingDetail entity : incomingMaterialPrintingDetails) {
//            //毛重 - 皮重
//            int round = (int) Math.round(entity.getGrossWeight());
//            int integer = Integer.parseInt(averageTare);
//            BigDecimal subtract = new BigDecimal(String.valueOf(round)).subtract(new BigDecimal(integer));
//            String s = subtract.toString();
//            entity.setNetWeight(Double.parseDouble(s));
//        }
////        for (IncomingMaterialPrintingDetail detail : incomingMaterialPrintingDetails) {
////            for (ResultMaterialVo materialVo : materialList) {
////                if (detail.getMaterialNumber().equals(materialVo.getMaterialNumber())) {
////                    //毛重 - 皮重
////                    int round = (int) Math.round(detail.getGrossWeight());
////                    int integer = Integer.parseInt(materialVo.getAverageTare());
////                    if (round >= integer) {
////                        //将该批次下的物料净重都进行修改
////
////                        BigDecimal subtract = new BigDecimal(String.valueOf(detail.getGrossWeight())).subtract(new BigDecimal(materialVo.getAverageTare()));
////                        detail.setNetWeight(Double.parseDouble(subtract.toString()));
////                    } else {
////                        //将该批次下的物料净重都进行修改
////                        detail.setNetWeight(detail.getGrossWeight());
////                    }
////                }
////            }
////        }
//        incomingMaterialPrintingDetailService.updateBatchById(incomingMaterialPrintingDetails);
//        return incomingMaterialPrintingMapper.updateById(incomingMaterialPrinting) > 0;
//    }

    /**
     * 根据唯一标识获取采购入库单号(feign调用)
     *
     * @param onlyMark
     * @return
     */
//    @Override
//    public String getReceiptNo(String onlyMark) {
//        IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getOnlyMark, onlyMark));
//        return incomingMaterialPrinting.getReceiptNo();
//    }

    /**
     * 根据批次号修改来料打印状态(feign调用)
     *
     * @param updatePrintStatusVo
     */
    @Override
    public void updatePrintStatus(UpdatePrintStatusVo updatePrintStatusVo) {
        IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectOne(new QueryWrapper<IncomingMaterialPrinting>().lambda().eq(IncomingMaterialPrinting::getBatchNo, updatePrintStatusVo.getBatchNumber()));
        incomingMaterialPrinting.setPrintStatus(2);
        incomingMaterialPrintingMapper.updateById(incomingMaterialPrinting);
        //同时获取对应明细下的数据，修改净重数量
        List<IncomingMaterialPrintingDetail> incomingMaterialPrintingDetails = incomingMaterialPrintingDetailMapper.selectList(new QueryWrapper<IncomingMaterialPrintingDetail>().lambda().eq(IncomingMaterialPrintingDetail::getBatchNo, incomingMaterialPrinting.getBatchNo()));
        double grossWeight = incomingMaterialPrintingDetails.get(0).getGrossWeight();
        for (IncomingMaterialPrintingDetail entity : incomingMaterialPrintingDetails) {
            entity.setNetWeight(grossWeight);
        }
        incomingMaterialPrintingDetailMapper.updateBatchById(incomingMaterialPrintingDetails);
    }

    /**
     * 委外打印一键入库
     */
    @Override
    public boolean oneKeyWarehousingSub(OneKeyWarehousingVo oneKeyWarehousingVo) {
        //通过库位编码获取仓库信息
        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(oneKeyWarehousingVo.getKwCode());
        //获取单据配置信息
        Long menuId = remoteMenuService.getIdByMenuName("委外入库");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);
        //获取委外打印信息
        IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectById(oneKeyWarehousingVo.getId());
        if (incomingMaterialPrinting.getPrintStatus() == 3) {
            //获取委外打印明细信息
            Page<IncomingMaterialPrintingDetailDto> page = new Page<>();
            Page<IncomingMaterialPrintingDetailDto> detailList = incomingMaterialPrintingDetailMapper.getDetailList(page, oneKeyWarehousingVo.getId());
            List<IncomingMaterialPrintingDetailDto> records = detailList.getRecords();
            //根据批次号查询委外入库明细
            List<SubcontractReceiptDetail> subcontractReceiptDetails = subcontractReceiptDetailMapper.selectList(new QueryWrapper<SubcontractReceiptDetail>()
                .lambda().eq(SubcontractReceiptDetail::getBatchNo, records.get(0).getBatchNo()));

            for (SubcontractReceiptDetail entity : subcontractReceiptDetails) {
                //如果配置了交接明细为待交接否则为已完成
                if (sysDocument.getDocHandoverMark() == 1) {
                    entity.setStatus(2);
                } else {
                    entity.setStatus(3);
                }
                entity.setWarehouseInBy(LoginHelper.getUsername());
                entity.setWarehouseMessage(warehouseCode.getCombinationName());
                entity.setWarehouseInTime(new Date());
            }

            subcontractReceiptDetailMapper.updateBatchById(subcontractReceiptDetails);

            //获取采购入库信息
            SubcontractReceipt subcontractReceipt = subcontractReceiptMapper.selectById(subcontractReceiptDetails.get(0).getSubcontractId());
            //单位
            MaterialUnitDto data1 = remoteUnitService.getUnitDataByCode(Long.parseLong(subcontractReceipt.getMaterialUnit())).getData();
            String unitQuantity = data1.getUnitQuantity();

            //获取仓库数据
            List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, subcontractReceiptDetails.get(0).getBatchNo()));
            for (WmsStockInfo entity : wmsStockInfoList) {

                entity.setWsiWarehourse(String.valueOf(warehouseCode.getCkId()));
                entity.setWsiReservoirArea(String.valueOf(warehouseCode.getKqId()));
                entity.setWsiStorageLoaction(String.valueOf(warehouseCode.getKwId()));
                entity.setWsiWarehourseInfo(warehouseCode.getCombinationName());
                entity.setWsiDocNum(subcontractReceipt.getReceiptNo());
                entity.setWsiConnectNum(subcontractReceipt.getSubcontractOrderNo());
                entity.setWsiGorssWeight(subcontractReceiptDetails.get(0).getGrossWeight());
                entity.setWsiNetWeight(subcontractReceiptDetails.get(0).getNetWeight());
                entity.setWsiMaterialStatus(2);
//                entity.setUnitPrice(subcontractReceipt.getUnitPrice());
                entity.setMaterialUnit(Long.parseLong(subcontractReceipt.getMaterialUnit()));
                if (unitQuantity != null) {
                    entity.setWsiMinunitNum(Integer.parseInt(unitQuantity));
                }
                entity.setWsiMaterialGrade("1");
            }
            //修改仓库数据
            wmsStockInfoMapper.updateBatchById(wmsStockInfoList);

            //获取入库总重量
            BigDecimal totalNetWeight = new BigDecimal(0);
            for (WmsStockInfo entity : wmsStockInfoList) {
                totalNetWeight = totalNetWeight.add(new BigDecimal(String.valueOf(entity.getWsiNetWeight())));
            }

            //校验该采购入库的全部明细状态是否都为已入库，如果不全是就修改为入库中，否则就修改为已完成
            List<SubcontractReceiptDetail> subcontractReceiptDetails1 = subcontractReceiptDetailMapper.selectList(new QueryWrapper<SubcontractReceiptDetail>()
                .lambda().eq(SubcontractReceiptDetail::getSubcontractId, subcontractReceipt.getId()));
            boolean isTrue = true;
            for (SubcontractReceiptDetail entity : subcontractReceiptDetails1) {
                if (entity.getStatus() == 1) {
                    isTrue = false;
                    break;
                }
            }
            //获取本次入库的重量与单据原重量之和
            double v;
            if (subcontractReceipt.getActualQuantity() != null) {
                BigDecimal add = totalNetWeight.add(new BigDecimal(subcontractReceipt.getActualQuantity()));
                v = Double.parseDouble(add.toString());
            } else {
                v = Double.parseDouble(totalNetWeight.toString());
            }
            //实际量
//            double aDouble = Double.parseDouble(byId.getActualQuantity());
            //每一次将实际量和计划量进行比较
            double plannedWeight = subcontractReceipt.getPlannedWeight();
            boolean b = (int) Math.round(v) >= (int) Math.round(plannedWeight);

            //如果实际量大于等于计划量并且采购入库的全部明细状态为已入库
            if (isTrue && b) {
                if (sysDocument.getDocExcessMark() == 1) {
                    subcontractReceipt.setStatus(2);
                } else {
                    subcontractReceipt.setStatus(4);
                }
            } else {
                subcontractReceipt.setStatus(2);
            }

//            double plannedWeight = byId.getPlannedWeight();
//            boolean b = (int) Math.round(v) >= (int) Math.round(plannedWeight);
//            if (isTrue && b) {
//                byId.setStatus(5);
//            } else {
//                byId.setStatus(2);
//            }
            subcontractReceipt.setActualQuantity(String.valueOf(v));
            subcontractReceipt.setWarehousingWarehouse(warehouseCode.getCkId());
            if (subcontractReceipt.getWarehousingNum() == 0) {
                subcontractReceipt.setWarehousingNum(subcontractReceiptDetails.size());
            } else {
                subcontractReceipt.setWarehousingNum(subcontractReceipt.getWarehousingNum() + subcontractReceiptDetails.size());
            }
            subcontractReceiptMapper.updateById(subcontractReceipt);

//            // 将数据回传至采购订单
//            UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
//            updatePurchaseOrderDataVo.setActualQuantity(String.valueOf(v));
//            updatePurchaseOrderDataVo.setPurchaseOrderNo(subcontractReceipt.getPurchaseOrderNo());
//            remotePurchaseOrderService.updateOrderData(updatePurchaseOrderDataVo);

            incomingMaterialPrinting.setPrintStatus(4);
            return incomingMaterialPrintingMapper.updateById(incomingMaterialPrinting) > 0;
        } else {
            throw new GlobalException("只能操作待入库的数据");
        }
    }

    /**
     * 完工打印一键入库
     */
    @Override
    public boolean oneKeyWarehousingWip(OneKeyWarehousingVo oneKeyWarehousingVo) {
        //通过库位编码获取仓库信息
        WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(oneKeyWarehousingVo.getKwCode());
        //获取单据配置信息
        Long menuId = remoteMenuService.getIdByMenuName("完工入库");
        SysDocumentResultDto sysDocument = remoteDocumentService.getInfoConfig(menuId);
        //获取完工打印信息
        IncomingMaterialPrinting incomingMaterialPrinting = incomingMaterialPrintingMapper.selectById(oneKeyWarehousingVo.getId());
        if (incomingMaterialPrinting.getPrintStatus() == 3) {
            //获取完工打印明细信息
            Page<IncomingMaterialPrintingDetailDto> page = new Page<>();
            Page<IncomingMaterialPrintingDetailDto> detailList = incomingMaterialPrintingDetailMapper.getDetailList(page, oneKeyWarehousingVo.getId());
            List<IncomingMaterialPrintingDetailDto> records = detailList.getRecords();
            //根据批次号查询完工入库明细
            List<WipCompletionDetail> wipCompletionDetails = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>()
                .lambda().eq(WipCompletionDetail::getBatchNo, records.get(0).getBatchNo()));

            for (WipCompletionDetail entity : wipCompletionDetails) {
                //如果配置了交接明细为待交接否则为已完成
                if (sysDocument.getDocHandoverMark() == 1) {
                    entity.setStatus(2);
                } else {
                    entity.setStatus(3);
                }
                entity.setWarehouseInBy(LoginHelper.getUsername());
                entity.setWarehouseMessage(warehouseCode.getCombinationName());
                entity.setWarehouseInTime(new Date());
            }

            wipCompletionDetailMapper.updateBatchById(wipCompletionDetails);

            //获取完工入库信息
            WipCompletion wipCompletion = wipCompletionMapper.selectById(wipCompletionDetails.get(0).getWipCompletionId());
            //单位
            MaterialUnitDto data1 = remoteUnitService.getUnitDataByCode(Long.parseLong(wipCompletion.getMaterialUnit())).getData();
            String unitQuantity = data1.getUnitQuantity();

            //获取仓库数据
            List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>()
                .lambda().eq(WmsStockInfo::getWsiMaterialBatch, wipCompletionDetails.get(0).getBatchNo()));
            for (WmsStockInfo entity : wmsStockInfoList) {

                entity.setWsiWarehourse(String.valueOf(warehouseCode.getCkId()));
                entity.setWsiReservoirArea(String.valueOf(warehouseCode.getKqId()));
                entity.setWsiStorageLoaction(String.valueOf(warehouseCode.getKwId()));
                entity.setWsiWarehourseInfo(warehouseCode.getCombinationName());
                entity.setWsiDocNum(wipCompletion.getReceiptNo());
                entity.setWsiConnectNum(wipCompletion.getMakingOrderNo());
                entity.setWsiGorssWeight(wipCompletionDetails.get(0).getGrossWeight());
                entity.setWsiNetWeight(wipCompletionDetails.get(0).getNetWeight());
                entity.setWsiMaterialStatus(2);
//                entity.setUnitPrice(subcontractReceipt.getUnitPrice());
                entity.setMaterialUnit(Long.parseLong(wipCompletion.getMaterialUnit()));
                if (unitQuantity != null) {
                    entity.setWsiMinunitNum(Integer.parseInt(unitQuantity));
                }
                entity.setWsiMaterialGrade("1");
            }
            //修改仓库数据
            wmsStockInfoMapper.updateBatchById(wmsStockInfoList);

            //获取入库总重量
            BigDecimal totalNetWeight = new BigDecimal(0);
            for (WmsStockInfo entity : wmsStockInfoList) {
                totalNetWeight = totalNetWeight.add(new BigDecimal(String.valueOf(entity.getWsiNetWeight())));
            }

            //校验该采购入库的全部明细状态是否都为已入库，如果不全是就修改为入库中，否则就修改为已完成
            List<WipCompletionDetail> wipCompletionDetails1 = wipCompletionDetailMapper.selectList(new QueryWrapper<WipCompletionDetail>()
                .lambda().eq(WipCompletionDetail::getWipCompletionId, wipCompletion.getId()));
            boolean isTrue = true;
            for (WipCompletionDetail entity : wipCompletionDetails1) {
                if (entity.getStatus() == 1) {
                    isTrue = false;
                    break;
                }
            }
            //获取本次入库的重量与单据原重量之和
            double v;
            if (wipCompletion.getActualQuantity() != null) {
                BigDecimal add = totalNetWeight.add(new BigDecimal(wipCompletion.getActualQuantity()));
                v = Double.parseDouble(add.toString());
            } else {
                v = Double.parseDouble(totalNetWeight.toString());
            }
            //实际量
//            double aDouble = Double.parseDouble(byId.getActualQuantity());
            //每一次将实际量和计划量进行比较
            double plannedWeight = wipCompletion.getPlannedWeight();
            boolean b = (int) Math.round(v) >= (int) Math.round(plannedWeight);

            //如果实际量大于等于计划量并且采购入库的全部明细状态为已入库
            if (isTrue && b) {
                if (sysDocument.getDocExcessMark() == 1) {
                    wipCompletion.setStatus(2);
                } else {
                    wipCompletion.setStatus(4);
                }
            } else {
                wipCompletion.setStatus(2);
            }

//            double plannedWeight = byId.getPlannedWeight();
//            boolean b = (int) Math.round(v) >= (int) Math.round(plannedWeight);
//            if (isTrue && b) {
//                byId.setStatus(5);
//            } else {
//                byId.setStatus(2);
//            }
            wipCompletion.setActualQuantity(String.valueOf(v));
            wipCompletion.setWarehousingWarehouse(warehouseCode.getCkId());
            if (wipCompletion.getWarehousingNum() == 0) {
                wipCompletion.setWarehousingNum(wipCompletionDetails.size());
            } else {
                wipCompletion.setWarehousingNum(wipCompletion.getWarehousingNum() + wipCompletionDetails.size());
            }
            wipCompletionMapper.updateById(wipCompletion);

//            // 将数据回传至采购订单
//            UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo = new UpdatePurchaseOrderDataVo();
//            updatePurchaseOrderDataVo.setActualQuantity(String.valueOf(v));
//            updatePurchaseOrderDataVo.setPurchaseOrderNo(subcontractReceipt.getPurchaseOrderNo());
//            remotePurchaseOrderService.updateOrderData(updatePurchaseOrderDataVo);

            incomingMaterialPrinting.setPrintStatus(4);
            return incomingMaterialPrintingMapper.updateById(incomingMaterialPrinting) > 0;
        } else {
            throw new GlobalException("只能操作待入库的数据");
        }
    }
}
